package poc.spring.xml;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import poc.bcsoi.utils.DateUtils;
import poc.spring.model.BcsoiCacheQueryParams;

/**
 *
 * @author Smatthai
 */
public class DdmsResourceEventHandler extends DefaultHandler {
    private String tempVal = "";
    private BcsoiCacheQueryParams bcqp;
    private StringBuffer curCharValue = new StringBuffer(2048);    
    private boolean isOrig = false;
	private DocumentBuilderFactory dbf;
	private DocumentBuilder db;
	private Document doc;

    
    public DdmsResourceEventHandler() {
    	try {
    		dbf = DocumentBuilderFactory.newInstance();
			db  = dbf.newDocumentBuilder();		
			doc = db.newDocument();
    	} catch (ParserConfigurationException pce) {
    		System.out.println("Error while trying to instantiate DocumentBuilder: " + pce.getMessage());
			pce.printStackTrace();
		}
    }

    @Override
    public void startElement(String nsURI, String strippedName, String tagName, Attributes attributes) throws SAXException {
        tempVal = "";
        if (tagName.equalsIgnoreCase("ddms:Resource")) {
            System.out.println("********************************\n");
            System.out.println("PARSING DDMS_RESOURCE DOCUMENT\n");
            System.out.println("********************************\n");
            bcqp = new BcsoiCacheQueryParams();
        } else if (tagName.equalsIgnoreCase("ddms:identifier")) {
            bcqp.setIdentityQualifier(attributes.getValue("ddms:qualifier"));
            bcqp.setIdentityValue(attributes.getValue("ddms:value"));
        } else if (tagName.equalsIgnoreCase("ddms:dates")) {
            bcqp.setCreatedtg(DateUtils.convertDateString(attributes.getValue("ddms:created")));
            bcqp.setExpirationDTG(DateUtils.convertDateString(attributes.getValue("ddms:validTil")));
        } else if (tagName.equalsIgnoreCase("bcsoi:OriginalData")) {
        	bcqp.setOrigXml(tempVal);        	
        	isOrig = true;        	
        	Element rootEle = doc.createElement(tagName);
    		doc.appendChild(rootEle);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) {
        tempVal = new String(ch, start, length);
        
        if (isOrig) {
        	curCharValue.append(ch, start, length);
        }
        System.out.print("Characters:    \"");
    	for (int i = start; i < start + length; i++) {
    	    switch (ch[i]) {
    	    case '\\':
    		System.out.print("\\\\");
    		break;
    	    case '"':
    		System.out.print("\\\"");
    		break;
    	    case '\n':
    		System.out.print("\n");
    		break;
    	    case '\r':
    		System.out.print("\r");
    		break;
    	    case '\t':
    		System.out.print("\t");
    		break;
    	    default:
    		System.out.print(ch[i]);
    		break;
    	    }
    	}
    	System.out.print("\"\n");

    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (qName.equalsIgnoreCase("ddms:Resource")) {
//            try {
//                ProcessOrder proc = new ProcessOrder();
//                owner.getOwner().sendResponse(proc.process(Integer.parseInt(qty), itemNum), replyTo);

//            } catch (NotEnoughItemInInventoryException ex) {
//                Logger.getLogger(OrderEventHandler.class.getName()).log(Level.SEVERE, null, ex);
//            } catch (NoSuchItemException ex) {
//                Logger.getLogger(OrderEventHandler.class.getName()).log(Level.SEVERE, null, ex);
//            }

        } else if (qName.equalsIgnoreCase("ddms:name")) {
        	bcqp.setAdapterName(tempVal);        
        } else if (qName.equalsIgnoreCase("ddms:WestBL")) {
        	bcqp.setWest(Double.parseDouble(tempVal));        
        } else if (qName.equalsIgnoreCase("ddms:EastBL")) {
        	bcqp.setEast(Double.parseDouble(tempVal));        
        } else if (qName.equalsIgnoreCase("ddms:SouthBL")) {
        	bcqp.setSouth(Double.parseDouble(tempVal));        
        } else if (qName.equalsIgnoreCase("ddms:NorthBL")) {
        	bcqp.setNorth(Double.parseDouble(tempVal));        
        } else if (qName.equalsIgnoreCase("bcsoi:OriginalData")) {
        	bcqp.setOrigXml(curCharValue.toString());
        	curCharValue.delete(0, 2048);
        	isOrig = false;
        }
        if ("".equals (uri))
    	    System.out.println("End element: " + qName);
    	else
    	    System.out.println("End element:   {" + uri + "}" + localName);

    }
    
    
    /** This method is called when warnings occur */
    public void warning(SAXParseException exception) {
      System.err.println("WARNING: line " + exception.getLineNumber() + ": "
          + exception.getMessage());
    }

    /** This method is called when errors occur */
    public void error(SAXParseException exception) {
      System.err.println("ERROR: line " + exception.getLineNumber() + ": "
          + exception.getMessage());
    }

    /** This method is called when non-recoverable errors occur. */
    public void fatalError(SAXParseException exception) throws SAXException {
      System.err.println("FATAL: line " + exception.getLineNumber() + ": "
          + exception.getMessage());
      throw (exception);
    }

    
	public BcsoiCacheQueryParams getBcqp() {
		return bcqp;
	}

	public void setBcqp(BcsoiCacheQueryParams bcqp) {
		this.bcqp = bcqp;
	}

}
